package com.example.springbooksystem.config;

import com.example.springbooksystem.model.ResponseData;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * Created with IntelliJ IDEA.
 * Description：
 *
 * @author: zxj
 * @date: 2024-01-31
 * @time: 12:22:29
 */
@ControllerAdvice
@Slf4j
public class ResponseAdvice implements ResponseBodyAdvice {

    @Autowired
    private ObjectMapper mapper;

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        /**
         * @return: boolean : true 表示启用统一返回结果的功能
         **/
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        // 如果返回结果是 ResponseData, 就直接返回即可
        if (body instanceof ResponseData) {
            return body;
        }


        // String 报错, 特殊处理, 使用 json 序列化
        if (body instanceof String) {
            try {
                return mapper.writeValueAsString(ResponseData.success(body));
            } catch (JsonProcessingException e) {
                log.error("json 序列化失败, e:{}",e);
                throw new RuntimeException(e);
            }
        }



        return ResponseData.success(body);
    }
}
